package com.scalar.chiptrack.operations.dataentry.inventory.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.dataentry.inventory.forms.InventoryDataEntryForm;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Sep 28, 2006
 * Time: 1:09:00 AM
 */
public class InventoryDataEntrySaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/invDataEntry.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {

       InventoryDataEntryForm  invDataEntryForm = ( InventoryDataEntryForm ) form;

        HashMap<String, String> errors = new HashMap<String, String>();
        HashMap<String, String> info = new HashMap<String, String>();
        String action = request.getParameter("action");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);


        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);

        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY))
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }
        ArrayList<LabelValueBean> invPartNumbersLableValueBeans = new ArrayList<LabelValueBean>();
        ArrayList<LabelValueBean> invLocationsLableValueBeans   = new ArrayList<LabelValueBean>();
        ArrayList<LabelValueBean> invLotNumberLabelValueBeans   = new ArrayList<LabelValueBean>();
        ArrayList<LabelValueBean> invfabLotNumberLabelValueBeans = new ArrayList<LabelValueBean>();

        ArrayList<LotDetails> invWipList = new ArrayList<LotDetails>();
        ArrayList processTypeList;


        LotDetails invLotDetails = invDataEntryForm.getInvLotDetails();
        invLotDetails.setProcessType( invDataEntryForm.getProcessType());
        invLotDetails.setProcessStepId(invDataEntryForm.getProcessStepId());
        invLotDetails.setLocationId(invDataEntryForm.getLocationId());
        invLotDetails.setLotId( invDataEntryForm.getLotId() );

        ArrayList binDataList = invLotDetails.getBinList();

        if (invLotDetails.getWaferQtyOut() != null && invLotDetails.getWaferQtyOut().trim().length() <= 0)
        {
            invLotDetails.setWaferQtyOut(null);
        }
        if (invLotDetails.getDateOut() != null && invLotDetails.getDateOut().trim().length() <= 0 )
        {
            invLotDetails.setDateOut(null);
        }
        if ( invLotDetails.getDieQtyOut() != null && invLotDetails.getDieQtyOut().trim().length() <= 0 )
        {
            invLotDetails.setDieQtyOut(null);
        }
        if (invLotDetails.getWaferQtyIn() != null && invLotDetails.getWaferQtyIn().trim().length() <= 0)
        {
            invLotDetails.setWaferQtyIn(null);
        }
        if ( invLotDetails.getDieQtyIn() != null && invLotDetails.getDieQtyIn().trim().length() <= 0 )
        {
            invLotDetails.setDieQtyIn(null);
        }
        if( invLotDetails.getFabLotNumber() == null )
        {
            invLotDetails.setFabLotNumber( invDataEntryForm.getFabLotNo() );
        }

        invWipList.add( invLotDetails );

        if( invWipList != null && invWipList.size() > 0 )
        {
            //Check FOR SAME LOT EXISTS
            try
            {   
            	if( invLotDetails.getProcessType() != null && invLotDetails.getProcessType().equalsIgnoreCase( LOCATION_TYPE_DIE_BANK ) )
            	{
                    int lotId = Integer.parseInt(invLotDetails.getLotId() );
                    int locId = Integer.parseInt( invLotDetails.getLocationId() );
                    int psId  = Integer.parseInt( invLotDetails.getProcessStepId() );

	            	if (  lotId <= 0 && DataEntryDAO.isLotNumberExists( null, psId, locId, invLotDetails.getVendorLotNumber(), invLotDetails.getProcessType() ))
	                {
	                	LotDetails lotDetails = new LotDetails();
	                    ArrayList<PartNumber> partNumberList = DataEntryDAO.getInvPartNumber(invDataEntryForm.getProcessType());
	                    for (int i = 0; i < partNumberList.size(); i++)
	                    {
	                        PartNumber partNumber = (PartNumber) partNumberList.get(i);
	                        invPartNumbersLableValueBeans.add(new org.apache.struts.util.LabelValueBean(partNumber.getPartNumber(), partNumber.getProcessStepId()));
	                    }
	                    ArrayList locationList= VendorDAO.getInventoryLocations(invDataEntryForm.getProcessType());
	
	                    for (int i = 0; i < locationList.size(); i++)
	                    {
	                        VendorLocation location = (VendorLocation) locationList.get(i);
	                        invLocationsLableValueBeans.add(new org.apache.struts.util.LabelValueBean(location.getLocationName(), location.getLocationID()));
	                    }
	
	                    ArrayList fabLotNumberList = DataEntryDAO.getRunningFabLotNumbersByPSTypeName(invDataEntryForm.getProcessStepId(), invDataEntryForm.getLocationId());
	                    for (int i = 0; i < fabLotNumberList.size(); i++) {
	                        Lot lot = (Lot) fabLotNumberList.get(i);
	                        invfabLotNumberLabelValueBeans.add(new org.apache.struts.util.LabelValueBean(lot.getFabLotnumber(), lot.getFabLotnumber()));
	                    }
	
	                   ArrayList lotList = DataEntryDAO.getRunningandHoldLotNumbersByPSTypeName( invDataEntryForm.getProcessStepId(), invDataEntryForm.getLocationId(), invDataEntryForm.getFabLotNo() );
	                    for (int i = 0; i < lotList.size(); i++)
	                    {
	                        Lot lot = (Lot) lotList.get(i);
	                        invLotNumberLabelValueBeans.add(new org.apache.struts.util.LabelValueBean( lot.getLotNumber(), lot.getLotId()));
	                    }
	
	
	                    request.setAttribute("processTypeList", lotDetails.getInventoryProcessList() );
	                    request.setAttribute("lotCategoryList", lotDetails.getLotCategoryType() );
	                    request.setAttribute("lotStatusList", lotDetails.getLotStatusType() );
	                    request.setAttribute("assemblyVendorsList", DataEntryDAO.loadAllVendorsByProcess( null , LOCATION_TYPE_ASSEMBLY ) );
	                    request.setAttribute("partNumbersList", invPartNumbersLableValueBeans);
	                    request.setAttribute("locationList", invLocationsLableValueBeans);
	                    request.setAttribute("invFabLotNoList", invfabLotNumberLabelValueBeans);
	                    request.setAttribute("invList", invLotNumberLabelValueBeans);
	
	                    errors.put( "Lot number <font color=blue>"+invLotDetails.getVendorLotNumber()+ "</font> already Exists", null );
	                    
	                    return mapping.findForward( "invDataEntry" );
	                }
            	}
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error While Checking the duplicate Lot information", null );
            }

            try
            {
                DataEntryDAO.saveDataEntryInventoryLot( null, invWipList, user.getUserName() );

                if ( binDataList != null && binDataList.size() > 0 )
                {
                    DataEntryDAO.saveDieBankBinInfo( null, invLotDetails );
                }
                info.put ( "Lot Information Saved", null );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error storing the Inventory Lot information", null );
            }
        }
        invDataEntryForm.setProcessType("0");
        invDataEntryForm.setProcessStepId("0");
        invDataEntryForm.setLocationId("0");
        invDataEntryForm.setLotId("0");
        invDataEntryForm.setFabLotNo("0");
        processTypeList = invLotDetails.getInventoryProcessList();
        request.setAttribute("processTypeList", processTypeList);
        request.setAttribute("action", action);

        return mapping.findForward( "invDataEntry" );
    }
}
